# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2022/9/1
# @Author  : moe@miku39.fun
# @File    : Cookies.py
# @Software: PyCharm
import os
import time

import qrcode
import requests


class GetCookies:
    def __init__(self, sess, system):
        self.sess = sess
        self.system = system

    def getLoginUrl(self):
        print("请打开B站进行扫码，二维码将于5秒后生成 (｀・ω・´)")
        time.sleep(5)
        url = "https://passport.bilibili.com/qrcode/getLoginUrl"
        header = {
            "referer": "https://passport.bilibili.com/login",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.67",
        }
        response = self.sess.get(url=url, headers=header).json()
        return response["data"]["url"], response["data"]["oauthKey"]

    def make_QR_code(self, data):
        if self.system == "posix":
            qr = qrcode.QRCode()
            qr.add_data(data)
            qr.make()
            qr.print_ascii(invert=True)
        elif self.system == "nt":
            qr = qrcode.make(data)
            qr.save("qrcode.png")
            os.system("qrcode.png")
            os.system("pause")
        else:
            print("未知系统，请手动填写Cookies ｡ﾟ(ﾟ´Д｀)ﾟ｡")

    def login(self, oauth_key):
        url = "https://passport.bilibili.com/qrcode/getLoginInfo"
        data = {"oauthKey": f"{oauth_key}", "gourl": ""}
        header = {
            "origin": "https://passport.bilibili.com",
            "referer": "https://passport.bilibili.com/login",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.67",
        }
        try:
            while True:
                response = self.sess.post(url=url, data=data, headers=header).json()
                if response["status"] is False and response["data"] == -4:
                    if self.system == "posix":
                        print("二维码未扫描 Σ_(꒪ཀ꒪」∠)_")
                    elif self.system == "nt":
                        print("二维码未扫描 Σ_(꒪ཀ꒪」∠)_")
                        os.system("qrcode.png")
                        os.system("pause")
                elif response["status"] is False and response["data"] == -5:
                    print("已扫描，未确认 (=・ω・=)")
                elif response["status"] is True:
                    print("已成功获取Cookies ✧(≖ ◡ ≖✿)")
                    os.remove("qrcode.png")
                    return self.sess.cookies.get_dict()
                time.sleep(5)
        except requests.exceptions.ConnectionError:
            pass
